<?php

namespace app\backend\logic;

use app\backend\model\Admin as AdminModel;
use app\backend\model\RolePermission;
use app\backend\validate\Admin as AdminValidate;

class Admin extends Logic
{

    /**
     * 登录
     *
     * @param string $username
     * @param string $password
     *
     * @return AdminModel|bool
     */
    public function login(string $username, string $password)
    {
        try
        {
            $admin = AdminModel::where(['username' => $username])->find();

            if ( ! $admin || ! hashPassword($password, $admin['password']))
            {
                throw new \Exception('用户名或者密码错误');
            }

            if ( ! $admin['status'])
            {
                throw new \Exception('该账号被限制登录');
            }

        } catch (\Exception $e)
        {
            $this->error = $e->getMessage();

            return false;
        }

        return $admin;
    }

    /**
     * 页面相应数据
     *
     * @param array  $where
     * @param string $order
     * @param int    $page
     * @param int    $row_num
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function tableList($where = [], $order = '', $page = 1, $row_num = 15): array
    {
        $model = (new AdminModel())->where($where)->with('role');
        $list = $model->order($order ?: 'id DESC')->page($page, $row_num)->select()->toArray();

        foreach ($list as &$v)
        {
            $v['role'] = trim(
                array_reduce(
                    $v['role'], function ($r, $rr)
                {
                    return $r.','.$rr['title'];
                }
                ), ','
            );
            $v['avatar'] = $v['avatar'] ?: '/static/backend/images/avatar.png';
            $v['_edit_visible'] = $v['id'] !== AdminModel::ADMIN;
            $v['_delete_visible'] = $v['id'] !== AdminModel::ADMIN;
        }
        unset($v);

        return [
            'count' => $model->count(),
            'list'  => $list,
        ];
    }

    /**
     * 保存用户
     *
     * @param array $post
     * @param array $group 角色
     *
     * @throws \think\db\concern\PDOException
     */
    public static function save(array $post, array $group = [])
    {
        try
        {
            $model = new AdminModel;
            $model->startTrans();

            $exists = isset($post['id']);
            validate(AdminValidate::class)->scene($exists ? 'edit' : 'create')->check($post);
            if ($exists)
            {
                if (isset($post['password']) && $post['password'] == '')
                {
                    unset($post['password']);
                }
                if ( ! $model->exists($exists)->save($post))
                {
                    throw new Exception();
                }
                $id = $post['id'];
            } else
            {
                $id = $model->insertGetId($post);
            }
            count($group) > 0 && self::addGroups($group, $id);
            $model->commit();
        } catch (Exception $e)
        {
            $model->rollback();

            return false;
        }

        return true;
    }


    public static function addGroups($group, $uid)
    {
        $list = [];
        foreach ( $group as $v ) {
            $list[] = [
                'admin_id' => $uid,
                'role_id' => $v,
            ];
        }
        $model = new RolePermission();
        $model->where(['admin_id' => $uid])->delete();
        if (count($list) > 0) {
            $model->insertAll($list);
        }
    }

}
